package org.jground.rx.ui.zk.viewControl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.codetable.Codetable;
import org.jground.codetable.DefaultCodetable;
import org.jground.codetable.DefaultCodetableElement;
import org.jground.rx.RXAttribute;
import org.jground.rx.RXCodetableFactory;
import org.jground.rx.RXSystem;
import org.jground.rx.RXTypeCodetable;
import org.jground.rx.RXView;
import org.jground.rx.ui.zk.UIFrame;
import org.jground.util.ArrayUtils;
import org.jground.util.L;
import org.jground.util.StringUtils;
import org.jground.zk.zulX.ComboboxX;

public class UIAttributeControlCodetable extends UIAttributeControlBase {

    private static Log logger = LogFactory.getLog(UIAttributeControlCodetable.class);

    public UIAttributeControlCodetable createNew(UIFrame uiFrame, RXView moControl) {
        return new UIAttributeControlCodetable(uiFrame, moControl);
    }

    

    // private CodeTableListModel codeTableModel;

    public UIAttributeControlCodetable() {}
    
    private  String codeTableName;
    private  ComboboxX codeTableUI;
    
    private UIAttributeControlCodetable(UIFrame uiFrame, RXView moControl) {
        super(uiFrame, moControl);
        RXAttribute moAttribute = moControl.getRXAttribute();
        RXTypeCodetable ctype = (RXTypeCodetable) moAttribute.getRXType().getBaseType();
         codeTableName = ctype.getCodeTableName();
        L.debug(logger, "codetable name", codeTableName);
        //
        codeTableUI = new ComboboxX(getCodetable());
        codeTableUI.setReadonly(true);
        
        // codeTableUI.setModel(codeTableModel = new CodeTableListModel(ct));
        add(codeTableUI);
    }
    
    protected Codetable getCodetable() {
        Codetable ct = null;
        try {
            ct = RXSystem.getInstance().getCtService().getCodetable(codeTableName, true);
        } catch (Exception e) {
            ct = new DefaultCodetable(codeTableName, e.toString(), new DefaultCodetableElement("--", e.toString()));
        }      
        return ct;
    }

    public void set(String... values) {
        clear();
        codeTableUI.setCodetable(getCodetable());
        if (ArrayUtils.isNotEmpty(values)) {
            try {
                String code = values[0];
                codeTableUI.setSelected(code);
            } catch (Exception e) {
                logger.warn(e, e);
            }
        }
    }

    public String[] get() {
        String code = codeTableUI.getSelected();
        return code == null ? StringUtils.EMPTY_STRING_ARRAY : ArrayUtils.toArray(code);
    }

    public void clear() {
        if (codeTableUI.getItemCount() > 0) {
            codeTableUI.setSelectedIndex(0);
        }
    }
}
